package com.ruoyi.common.config;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * 七牛云配置
 *
 * @author huzhimin
 */
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiNiuConfig {
    private  Logger logger = LoggerFactory.getLogger(QiNiuConfig.class);
    /**
     * AccessKey
     */
    private  String accessKey;
    /**
     * SecretKey
     */
    private  String secretKey;
    /**
     * 存储区域
     */
    private  Region region;

    /**
     * 存储空间
     */
    private  String bucket;
    /**
     * 访问地址
     */
    private  String httpUrl;


    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public Region getRegion() {
        return region;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public String getHttpUrl() {
        return httpUrl;
    }

    public void setHttpUrl(String httpUrl) {
        this.httpUrl = httpUrl;
    }

    public void setRegion(String region) {
        switch (region) {
            case "z0":
                this.region = Region.region0();
                break;
            case "z1":
                this.region = Region.region1();
                break;
            case "z2":
                this.region = Region.region2();
                break;
            case "na0":
                this.region = Region.regionNa0();
                break;
            case "as0":
                this.region = Region.regionAs0();
                break;
            default:
                this.region = Region.region0();
                break;
        }
    }


    /**
     * 图片前缀
     */
    private static String FILE_SUFFIX = "zm_img_";

    /**
     * 七牛云上传图片
     *
     * @param file
     * @return
     */
    public  String uploadQiNiu(MultipartFile file) {
        return uploadQiNiu(file, "");
    }

    public String uploadQiNiu(String file) {
        return uploadQiNiu(file, "");
    }


    public String uploadQiNiu(String file, String fileName) {
        String suffix = file.substring(file.lastIndexOf('.'));
        String key = StringUtils.isEmpty(fileName) ? FILE_SUFFIX + System.currentTimeMillis() + suffix : fileName;
        return save(file, key);
    }
    /**
     * 七牛云上传图片 自定义文件名
     *
     * @param file
     * @return
     */

    public  String uploadQiNiu(MultipartFile file, String fileName) {
        String suffix = FileUploadUtils.getExtension(file);
        String key = StringUtils.isEmpty(fileName) ? FILE_SUFFIX + System.currentTimeMillis() +"."+ suffix : fileName;
        return save(file, key);
    }
    /**
     * 保存到七牛云
     * @param file
     * @param key
     * @return
     */
    public  String save(MultipartFile file, String key) {
        try {
            // 获取机房信息// 构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(this.region);
            UploadManager uploadManager = new UploadManager(cfg);

            // 对账户进行认证
            Auth auth = Auth.create(this.accessKey, this.secretKey);
            String upToken = auth.uploadToken(this.bucket);

            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(file.getBytes());
            Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            Response r = e.response;
            // 不抱错其实就已经是上传成功
            logger.error("QiNiu Upload Error :", r.toString());
            try {
                logger.error("QiNiu Upload  Error body :", r.bodyString());
            } catch (QiniuException ex2) {
                //ignore 忽略即可
            }
        } catch (Exception e) {
            logger.error("QiNiu Error :", e.toString());
        }
        return "";
    }

    /**
     * 保存到七牛云
     * @param file
     * @param key
     * @return
     */
    public  String save(String file, String key) {
        try {
            // 获取机房信息// 构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(this.region);
            UploadManager uploadManager = new UploadManager(cfg);
            // 对账户进行认证
            Auth auth = Auth.create(this.accessKey, this.secretKey);
            String upToken = auth.uploadToken(this.bucket);
            Response response = uploadManager.put(file, key, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            Response r = e.response;
            // 不抱错其实就已经是上传成功
            logger.error("QiNiu Upload Error :", r.toString());
            try {
                logger.error("QiNiu Upload  Error body :", r.bodyString());
            } catch (QiniuException ex2) {
                //ignore 忽略即可
            }
        } catch (Exception e) {
            logger.error("QiNiu Error :", e.toString());
        }
        return "";
    }
}
